package com.acme.bankapp.service.feed;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.bank.Gender;
import com.acme.bankapp.domain.bank.accounts.Account;
import com.acme.bankapp.domain.bank.accounts.CheckingAccount;
import com.acme.bankapp.domain.bank.accounts.SavingAccount;
import com.acme.bankapp.domain.bank.exceptions.ClientExistsException;
import com.acme.bankapp.service.app.BankService;

public class FeedService {
	public static void readClientsFromFeed(BankService bank, File file) throws FileNotFoundException {
		Scanner scin = new Scanner(new FileInputStream(file));
		Pattern pat = Pattern.compile("account=(?<account>[cs]);" +
				"balance=(?<balance>[0-9]*.?[0-9]+);" +
				"overdraft=(?<balance>[0-9]*.?[0-9]+);" +
				"name=(?<name>[A-Za-z\\s]+);gender=(?<gender>[fm]);");
		while (scin.hasNext()) {
			Matcher mr = pat.matcher(scin.nextLine());
			if (!mr.matches()) continue;
			Client c = new Client(mr.group("name"), Gender.getGender(mr.group("gender")));
			try {
				double overdraft = Double.parseDouble(mr.group("overdraft"));
				double balance = Double.parseDouble(mr.group("balance"));
				Account a = (Account) (("c".equals(mr.group("account"))) ?
						new CheckingAccount(balance, overdraft) :
						new SavingAccount(balance));
				c.addAccount(a);
				bank.addClient(c);
			} catch (ClientExistsException e) {
				e.printStackTrace();
			}
		}
		scin.close();
	}
}
